package com.cs.controller.imgs;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;

@RestController
@RequestMapping("/img")
public class ImageController {
        @GetMapping("/{imageName:.+}")
        @ResponseBody
        public ResponseEntity<Resource> getImage(@PathVariable String imageName) throws IOException {
            String str=imageName.split("\\.")[1];
            MediaType type=null;
            switch (str){
                case "jpg":
                    type=MediaType.IMAGE_JPEG;break;
                case "jpeg":
                    type=MediaType.IMAGE_JPEG;break;
                case "png":
                    type=MediaType.IMAGE_PNG;break;
                case "gif":
                    type=MediaType.IMAGE_GIF;break;
                default:
                    break;
            }
            String path = "file:/D:/csDemoImage/" + imageName;
            Resource resource = new UrlResource(path);
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .contentType(type)
                        .body(resource);
            } else {
                System.out.println("错");
                return ResponseEntity.notFound().build();
            }
        }

}
